package com.example.springboot.controller;

import com.example.springboot.config.redis.lock.DistributedLock;
import com.example.springboot.config.redis.utils.RedissonUtil;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/5/22 17:11
 */
@RestController
@RequestMapping("/redisson")
public class RedissonController {
    @Autowired
    private DistributedLock distributedLock;

    @GetMapping("/lock")
    public String get(String lockKey) throws InterruptedException {
        RedissonUtil.setDistributedLock(distributedLock);
        // 加锁
        RLock lock = RedissonUtil.lock(lockKey);
        //
        System.out.println("加锁成功");
        // s睡眠五秒
        TimeUnit.SECONDS.sleep(5);
        // 解锁
        lock.unlock();
        return "解锁成功" + ThreadLocalRandom.current().nextInt(5);
    }

    /**
     * 没有锁竞争的时候验证
     *
     * @param lockKey
     * @return
     */
    @GetMapping("/lock1")
    public String get1(String lockKey) {
        lockKey = lockKey + ThreadLocalRandom.current().nextInt(5);
        RedissonUtil.setDistributedLock(distributedLock);
        // 加锁
        RLock lock = RedissonUtil.lock(lockKey);
        //
        System.out.println("加锁成功");
        // 解锁
        lock.unlock();
        return "get1解锁成功" + lockKey;
    }
}
